
import Vue from 'vue';
import index from './index.vue';
import mtracker from '@src/util/mtracker';
import VueClipboard from 'vue-clipboard2'

import { getAsyncDoMySelfInitData, getAsyncDoMySelfInitData2 } from '@src/api/InitDataApi'
import qs from 'qs';
import { setTabTitle } from '@src/util/tabTitle.js';
import { RESOURCE_PREFIX } from '@src/util/linkSwitch';

mtracker();

Vue.filter('usual-num', function (value) {
  // 返回处理后的值
  if (!value) return '0'
  if (value * 1 > 10000) {
    return `${value / 10000}万`
  }
  return value
})

Vue.use(VueClipboard)

const componentItem = (initData) => {
  return {
    data() {
      return {
        initData
      }
    },
    components: {
      homeView: index
    },
    render(h) {
      return (
        <homeView initData={this.initData} />
      )
    }
  }
}

Vue.component('async-component', function(resolve) {
  
  // 需要加loading 打开此注释
  // const instance = Loading.service({ fullscreen: true });
  
  let query = qs.parse(window.location.search.substr(1));
  const params = Object.assign({}, query, {})
  let path = window.location.pathname;
  if(path.indexOf(RESOURCE_PREFIX) > -1) path = path.replace(RESOURCE_PREFIX, '')
  const fetchInitData = path == '/setting/doMyself/doMyselfSet' ? getAsyncDoMySelfInitData : getAsyncDoMySelfInitData2

  fetchInitData(params).then(result => {
    let initJSON = ''
    try {
      initJSON = JSON.parse((result && result.data && result.data.initJson))
    } catch (error) {
      console.error('initJSON 解析失败')
    }

    const initData = initJSON || {}
    const title = (result && result.data && result.data.title) || ''
    const isSuccess = result.succ || result.success
    
    if (!isSuccess) {
      window.location.href = '/500'
      return 
    }
    
    try {
      window._init = JSON.stringify(initData)
    } catch (error) {
      console.error('initData 赋值失败')
    }
    
    // 需要加loading 打开此注释
    // instance.close();
 
    // if (window.frameElement) {
    //   const currentTabId = window.frameElement.dataset.id;
    //   platform.setTabTitle({
    //     id: currentTabId,
    //     title
    //   })
    // }

    setTabTitle()
    resolve(componentItem(initData))
    
  }).catch(error => {
    console.error(error)
    window.location.href = '/500'
  })
  
});

let app = {
  render(h) {
    return <async-component />
  }
}

export default app;

